import React, { useState } from 'react';
import { 
  Card, 
  Row, 
  Col, 
  Avatar, 
  Typography, 
  Statistic, 
  Button, 
  Empty,
  Tag,
  Space,
  Modal,
  Drawer
} from 'antd';
import { 
  UserOutlined, 
  SkinOutlined, 
  SafetyOutlined,
  ThunderboltOutlined,
  AimOutlined,
  RocketOutlined,
  ShoppingOutlined,
  SwapOutlined
} from '@ant-design/icons';
import { EquipmentSlots, InventoryItem, EquipmentType } from '../types/game';
import { EquipmentManager } from '../utils/equipmentManager';
import { ItemManager } from '../utils/itemManager';

const { Title, Text } = Typography;

interface EquipmentDrawerProps {
  equipment: EquipmentSlots;
  inventory: InventoryItem[];
  open: boolean;
  onClose: () => void;
  onEquipItem: (item: InventoryItem, slotType: EquipmentType) => void;
  onUnequipItem: (slotType: EquipmentType) => void;
}

const EquipmentDrawer: React.FC<EquipmentDrawerProps> = ({
  equipment,
  inventory,
  open,
  onClose,
  onEquipItem,
  onUnequipItem
}) => {
  const [selectedSlot, setSelectedSlot] = useState<EquipmentType | null>(null);
  const [equipModalVisible, setEquipModalVisible] = useState(false);

  // 计算当前装备属性
  const calculatedStats = EquipmentManager.calculateStats(equipment);

  // 获取指定类型的可装备物品
  const getEquippableItems = (slotType: EquipmentType) => {
    return inventory.filter(item => EquipmentManager.canEquipItem(item, slotType));
  };

  // 处理装备槽位点击
  const handleSlotClick = (slotType: EquipmentType) => {
    setSelectedSlot(slotType);
    setEquipModalVisible(true);
  };

  // 处理装备选择
  const handleEquipSelect = (item: InventoryItem) => {
    if (selectedSlot) {
      onEquipItem(item, selectedSlot);
      setEquipModalVisible(false);
    }
  };

  // 处理卸下装备
  const handleUnequip = (slotType: EquipmentType) => {
    onUnequipItem(slotType);
  };

  // 装备槽位渲染
  const renderEquipmentSlot = (
    slotType: EquipmentType, 
    equipment: InventoryItem | null, 
    icon: React.ReactNode,
    span: number = 8
  ) => {
    const slotName = EquipmentManager.getSlotDisplayName(slotType);
    
    return (
      <Col span={span} key={slotType}>
        <Card
          hoverable
          size="small"
          title={
            <Space>
              {icon}
              <Text strong>{slotName}</Text>
            </Space>
          }
          extra={
            equipment && (
              <Button 
                size="small" 
                type="text" 
                onClick={() => handleUnequip(slotType)}
              >
                卸下
              </Button>
            )
          }
          onClick={() => handleSlotClick(slotType)}
          style={{ 
            minHeight: 120,
            cursor: 'pointer',
            border: equipment ? '2px solid #1890ff' : '2px dashed #d9d9d9'
          }}
        >
          {equipment ? (
            <div>
              <Tag color={ItemManager.getRarityColor(equipment.rarity)}>
                {equipment.name}
              </Tag>
              <div style={{ marginTop: 8 }}>
                {equipment.equipmentStats && (
                  <Space direction="vertical" size={2}>
                    {equipment.equipmentStats.attack && (
                      <Text type="secondary">
                        攻击: +{equipment.equipmentStats.attack}
                      </Text>
                    )}
                    {equipment.equipmentStats.defense && (
                      <Text type="secondary">
                        防御: +{equipment.equipmentStats.defense}
                      </Text>
                    )}
                    {equipment.equipmentStats.accuracy && (
                      <Text type="secondary">
                        精准: +{equipment.equipmentStats.accuracy}
                      </Text>
                    )}
                  </Space>
                )}
              </div>
            </div>
          ) : (
            <Empty
              image={<div style={{ fontSize: 24, opacity: 0.3 }}>{icon}</div>}
              description="未装备"
              style={{ margin: 0 }}
            />
          )}
        </Card>
      </Col>
    );
  };

  return (
    <Drawer
      title="装备管理"
      placement="left"
      open={open}
      onClose={onClose}
      width={720}
      destroyOnClose
    >
      {/* 角色头像和基础信息 */}
      <Card style={{ marginBottom: 16 }}>
        <Row gutter={16} align="middle">
          <Col span={4}>
            <Avatar size={48} icon={<UserOutlined />} />
          </Col>
          <Col span={20}>
            <Title level={5} style={{ margin: 0 }}>装备管理</Title>
            <Text type="secondary" style={{ fontSize: '12px' }}>管理你的战术装备，提升战斗能力</Text>
          </Col>
        </Row>
      </Card>

      {/* 属性统计 */}
      <Card title="装备属性" style={{ marginBottom: 16 }} size="small">
        <Row gutter={8}>
          <Col span={8}>
            <Statistic
              title="总攻击力"
              value={calculatedStats.totalAttack}
              prefix={<ThunderboltOutlined style={{ color: '#f50' }} />}
              valueStyle={{ color: '#f50', fontSize: '16px' }}
            />
          </Col>
          <Col span={8}>
            <Statistic
              title="总防御力"
              value={calculatedStats.totalDefense}
              prefix={<SafetyOutlined style={{ color: '#1890ff' }} />}
              valueStyle={{ color: '#1890ff', fontSize: '16px' }}
            />
          </Col>
          <Col span={8}>
            <Statistic
              title="精准度"
              value={calculatedStats.totalAccuracy}
              prefix={<AimOutlined style={{ color: '#52c41a' }} />}
              valueStyle={{ color: '#52c41a', fontSize: '16px' }}
            />
          </Col>
        </Row>
        <Row gutter={8} style={{ marginTop: 8 }}>
          <Col span={8}>
            <Statistic
              title="速度"
              value={calculatedStats.totalSpeed}
              prefix={<RocketOutlined style={{ color: '#faad14' }} />}
              valueStyle={{ color: '#faad14', fontSize: '16px' }}
            />
          </Col>
          <Col span={8}>
            <Statistic
              title="背包容量"
              value={calculatedStats.inventoryCapacity}
              prefix={<ShoppingOutlined style={{ color: '#722ed1' }} />}
              valueStyle={{ color: '#722ed1', fontSize: '16px' }}
            />
          </Col>
          <Col span={8}>
            <Statistic
              title="弹药容量"
              value={calculatedStats.ammoCapacity}
              prefix={<SwapOutlined style={{ color: '#eb2f96' }} />}
              valueStyle={{ color: '#eb2f96', fontSize: '16px' }}
            />
          </Col>
        </Row>
      </Card>

      {/* 装备槽位 */}
      <Card title="装备槽位">
        <Row gutter={16} style={{ marginBottom: 16 }}>
          {/* 第一行：头部、身体、背包 */}
          {renderEquipmentSlot(
            EquipmentType.HEAD, 
            equipment.head, 
            <SkinOutlined />,
            8
          )}
          {renderEquipmentSlot(
            EquipmentType.BODY, 
            equipment.body, 
            <SafetyOutlined />,
            8
          )}
          {renderEquipmentSlot(
            EquipmentType.BACKPACK, 
            equipment.backpack, 
            <ShoppingOutlined />,
            8
          )}
        </Row>

        <Row gutter={16} style={{ marginBottom: 16 }}>
          {/* 第二行：主武器、副武器 */}
          {renderEquipmentSlot(
            EquipmentType.PRIMARY_WEAPON, 
            equipment.primaryWeapon, 
            <ThunderboltOutlined />,
            12
          )}
          {renderEquipmentSlot(
            EquipmentType.SECONDARY_WEAPON, 
            equipment.secondaryWeapon, 
            <AimOutlined />,
            12
          )}
        </Row>

        <Row gutter={16}>
          {/* 第三行：刀、弹挂 */}
          {renderEquipmentSlot(
            EquipmentType.KNIFE, 
            equipment.knife, 
            <RocketOutlined />,
            12
          )}
          {renderEquipmentSlot(
            EquipmentType.AMMO_POUCH, 
            equipment.ammoPouch, 
            <SwapOutlined />,
            12
          )}
        </Row>
      </Card>

      {/* 装备选择模态框 */}
      <Modal
        title={`选择${selectedSlot ? EquipmentManager.getSlotDisplayName(selectedSlot) : '装备'}`}
        open={equipModalVisible}
        onCancel={() => setEquipModalVisible(false)}
        footer={null}
        width={600}
      >
        {selectedSlot && (
          <div>
            <Text type="secondary" style={{ marginBottom: 16, display: 'block' }}>
              从仓库中选择要装备的物品
            </Text>
            
            <div style={{ maxHeight: 400, overflowY: 'auto' }}>
              {getEquippableItems(selectedSlot).length === 0 ? (
                <Empty 
                  description="仓库中没有可装备的物品"
                  style={{ margin: '40px 0' }}
                />
              ) : (
                <Row gutter={[16, 16]}>
                  {getEquippableItems(selectedSlot).map((item, index) => (
                    <Col span={24} key={`${item.id}-${index}`}>
                      <Card
                        hoverable
                        size="small"
                        onClick={() => handleEquipSelect(item)}
                        style={{ cursor: 'pointer' }}
                      >
                        <Row align="middle">
                          <Col span={16}>
                            <Space direction="vertical" size={4}>
                              <div>
                                <Tag color={ItemManager.getRarityColor(item.rarity)}>
                                  {item.name}
                                </Tag>
                              </div>
                              <Text type="secondary" style={{ fontSize: '12px' }}>
                                {item.description}
                              </Text>
                            </Space>
                          </Col>
                          <Col span={8} style={{ textAlign: 'right' }}>
                            {item.equipmentStats && (
                              <Space direction="vertical" size={2}>
                                {item.equipmentStats.attack && (
                                  <Text style={{ fontSize: '12px' }}>
                                    攻击: +{item.equipmentStats.attack}
                                  </Text>
                                )}
                                {item.equipmentStats.defense && (
                                  <Text style={{ fontSize: '12px' }}>
                                    防御: +{item.equipmentStats.defense}
                                  </Text>
                                )}
                                {item.equipmentStats.accuracy && (
                                  <Text style={{ fontSize: '12px' }}>
                                    精准: +{item.equipmentStats.accuracy}
                                  </Text>
                                )}
                              </Space>
                            )}
                          </Col>
                        </Row>
                      </Card>
                    </Col>
                  ))}
                </Row>
              )}
            </div>
          </div>
        )}
      </Modal>
    </Drawer>
  );
};

export default EquipmentDrawer;